package com.zwzc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateFormatUtil {
    /**
     * @param source 源字符串
     * @return
     * @Title: parseDate
     * @Description:TODO(转换日期类型)
     * @author hejialun
     */
    public static Date parseDate(String source) {
        if (source == null || source.trim().equals("")) {
            return null;
        }
        String datestr = source.trim();
        // 处理日期格式
        String regex = "^(\\d+)[-/\\\\.年 ](\\d+)[-/\\\\.月 ](\\d+)日?";
        datestr = datestr.replaceAll(regex, "$1-$2-$3");
        datestr = datestr.replaceFirst("^(\\d+)-(\\d+)-(\\d+) +(\\d+):(\\d+):(\\d+)$", "$1-$2-$3 $4:$5:$6.000")
                .replaceFirst("^(\\d+)-(\\d+)-(\\d+)$", "$1-$2-$3 00:00:00.000");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
            Date date = dateFormat.parse(datestr);
            return date;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param source 源字符串
     * @return
     * @Title: parseLocalDateTime
     * @Description:TODO(转换java8日期类型)
     * @author hejialun
     */
    public static LocalDateTime parseLocalDateTime(String source) {
        return dateToLocalDateTime(parseDate(source));
    }


    /**
     * @param source 源字符串
     * @return
     * @Title: parseLocalDate
     * @Description:TODO(转换java8日期类型)
     * @author hejialun
     */
    public static LocalDate parseLocalDate(String source) {
        return dateToLocalDate(parseDate(source));
    }


    /**
     * @param localDateTime
     * @return
     * @Title: localDateTimeToDate
     * @Description:TODO(java8LocalDateTime转java.util.Date)
     * @author hejialun
     */
    public Date localDateTimeToDate(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }


    /**
     * @param date
     * @return
     * @Title: dateToLocalDateTime
     * @Description:TODO(java.util.Date转java8LocalDateTime)
     * @author hejialun
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }


    /**
     * @param date
     * @return
     * @Title: dateToLocalDate
     * @Description:TODO(java.util.Date转java8LocalDate)
     * @author hejialun
     */
    public static LocalDate dateToLocalDate(Date date) {
        if (date == null) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }


}
